package upload

import (
	"cloud-storage/lib"
	"cloud-storage/utils"
	"errors"
	"go.uber.org/zap"
	"io"
	"mime/multipart"
	"os"
	"path"
)

func UploadFile(file *multipart.FileHeader, filepath string) (string, error) {
	//对文件名加密
	fileName := utils.GetName(file.Filename)
	//获取文件全路径
	fullPath := utils.GetFullPath(filepath)
	src := fullPath + fileName
	//判断文件的大小和类型是否合适
	if !utils.CheckSize(file, lib.ImagesSetting.ImageMaxSize) && utils.GetFileTypeInt(path.Ext(file.Filename)) == 2 {
		//创建目录
		err := utils.CheckDir(fullPath)
		if err != nil {
			return "", err
		} else {
			//上传文件到本地
			f, openError := file.Open() // 读取文件
			if openError != nil {
				zap.L().Error("function file.Open() Filed", zap.Any("err", openError.Error()))
				return "", errors.New("function file.Open() Filed, err:" + openError.Error())
			}
			defer f.Close() // 创建文件 defer 关闭
			out, createErr := os.Create(src)
			if createErr != nil {
				zap.L().Error("function os.Create() Filed", zap.Any("err", createErr.Error()))

				return "", errors.New("function os.Create() Filed, err:" + createErr.Error())
			}
			defer out.Close() // 创建文件 defer 关闭

			_, copyErr := io.Copy(out, f) // 传输（拷贝）文件
			if copyErr != nil {
				zap.L().Error("function io.Copy() Filed", zap.Any("err", copyErr.Error()))
				return "", errors.New("function io.Copy() Filed, err:" + copyErr.Error())
			}
		}
	}
	return lib.AppSetting.PrefixUrl + filepath + fileName, nil
}
